import React, { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { routes, type CustomRoute } from './routes';
import { Spin } from 'antd';

interface RouterGuardProps {
  children: React.ReactNode;
}

const RouterGuard: React.FC<RouterGuardProps> = ({ children }) => {
  const location = useLocation();
  const navigate = useNavigate();
  const { isAuthenticated, isLoading, user } = useAuth();

  useEffect(() => {
    // 如果正在加载认证状态，不做任何操作
    if (isLoading) {
      return;
    }

    // 查找当前路由配置
    const currentRoute = routes.find((route: CustomRoute) => {
      if (route.path === '*') return false;
      if (route.path === location.pathname) return true;
      // 处理动态路由匹配
      if (route.path.includes(':')) {
        const routePattern = route.path.replace(/:[^/]+/g, '[^/]+');
        const regex = new RegExp(`^${routePattern}$`);
        return regex.test(location.pathname);
      }
      return false;
    });

    // 如果没有找到匹配的路由，跳转到404
    if (!currentRoute && location.pathname !== '/404') {
      navigate('/404', { replace: true });
      return;
    }

    // 检查路由是否需要认证
    const requiresAuth = currentRoute?.meta?.requiresAuth ?? true;

    if (requiresAuth && !isAuthenticated) {
      // 需要认证但未登录，跳转到登录页
      navigate('/login', { 
        replace: true,
        state: { from: location.pathname }
      });
      return;
    }

    if (!requiresAuth && isAuthenticated && location.pathname === '/login') {
      // 已登录用户访问登录页，重定向到首页
      const from = location.state?.from || '/';
      navigate(from, { replace: true });
      return;
    }

    // 检查用户角色权限（如果配置了）
    if (currentRoute?.meta?.roles && user) {
      const hasRequiredRole = currentRoute.meta.roles.some(role => 
        user.roles?.includes(role)
      );
      
      if (!hasRequiredRole) {
        navigate('/403', { replace: true });
        return;
      }
    }

    // 检查用户权限（如果配置了）
    if (currentRoute?.meta?.permissions && user) {
      const hasRequiredPermission = currentRoute.meta.permissions.some(permission => 
        user.permissions?.includes(permission)
      );
      
      if (!hasRequiredPermission) {
        navigate('/403', { replace: true });
        return;
      }
    }

    // 设置页面标题
    if (currentRoute?.meta?.title) {
      document.title = `${currentRoute.meta.title} - 管理系统`;
    }

  }, [location.pathname, location.state, isAuthenticated, isLoading, user, navigate]);

  // 显示加载状态
  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen space-y-4">
        <Spin size="large" />
        <div className="text-gray-600">加载中...</div>
      </div>
    );
  }

  return <>{children}</>;
};

export default RouterGuard;